//
//  FIPBulbVC.m
//  fireplace
//
//  Created by XiangDongMBP on 2017/3/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "FIPBulbVC.h"
#import "EFCircularSlider.h"
#import "UIColor+XDHex.h"
#import "FIPTcpSocket.h"
#import "MBProgressHUD+XDPrompt.h"

@interface FIPBulbVC ()
@property (weak, nonatomic) IBOutlet EFCircularSlider *circlularSlider;
@property (weak, nonatomic) IBOutlet UIButton *fireBtn;
@property (weak, nonatomic) IBOutlet UILabel *powerLabel;

@property (strong, nonatomic) FIPTcpSocket *refrshSocket;   //!< 回调使用的句柄
@property (strong, nonatomic) FIPTcpSocket *hotSocket;      //!< 加热的socket

@end

static NSUInteger const kSliderHandleColor = 0xE6CE30;       // 边框颜色
static NSInteger const kHudDelay = 0.5;                      // HUD隐藏的时间

@implementation FIPBulbVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    
}

- (void)initSubViews {
    self.circlularSlider.lineWidth = 40;
    self.circlularSlider.handleColor = [UIColor xd_colorWithHex:kSliderHandleColor];
    self.circlularSlider.filledColor = [UIColor clearColor];
    self.circlularSlider.unfilledColor = [UIColor clearColor];
    self.circlularSlider.handleType = EFBigCircle;
    self.circlularSlider.continuous = NO;
    self.circlularSlider.minimumValue = 0.0f;
    self.circlularSlider.maximumValue = 1.0f;
    [self.circlularSlider addTarget:self action:@selector(circlularSlider:) forControlEvents:UIControlEventValueChanged];
    
    self.fireBtn.layer.masksToBounds = YES;
    self.fireBtn.layer.cornerRadius = CGRectGetWidth(self.fireBtn.bounds) / 2.0;
    self.fireBtn.clipsToBounds = YES;
//    [self.fireBtn addTarget:self action:@selector(fireBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self requestSyncData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - delegate
#pragma mark - event response
- (void)fireBtnTapped:(UIButton *)btn {
    btn.selected = !btn.selected;
}

- (void)circlularSlider:(EFCircularSlider *)slider {
    NSLog(@"抬起时slider的值 %f", slider.currentValue);
    NSInteger hotA[4] = {2, 3, 0, 1};
    NSInteger hotIndex = (NSInteger)(slider.currentValue * 4.0);
    hotIndex = (hotIndex > 3) ? 3 : hotIndex;
    
    [self refreshHotView:hotA[hotIndex]];
    [self requestRGBWithHot:hotA[hotIndex]];
}

#pragma mark - private methods
- (void)refreshWholeViewWithData:(NSData *)data {
    if (data.length != 21) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"同步数据错误"];
        return;
    }
    
    NSLog(@"同步成功接收到的数据: %@", data);
    
    for (NSInteger i = 0; i<21; i+=7) {
        Byte byte[7];
        [data getBytes:byte range:NSMakeRange(i, 7)];
        if ((byte[0] == 0xA5) && (byte[2] == 0x01)) {
            NSLog(@"加热状态 = %d", byte[3]);
            [self refreshHotView:byte[3]];
            [self refreshHotSlider:byte[3]];
        }
        if ((byte[0] == 0xA5) && (byte[2] == 0x02)) {
            NSLog(@"RGB状态, L_ON = %d, L_SPEED = %d, L_BRIGHT = %d", byte[3], byte[4], byte[5]);
        }
        if ((byte[0] == 0xA5) && (byte[2] == 0x03)) {
            NSLog(@"RGB模式, MODE = %d, R_VAL = %d, G_VAL = %d, B_VAL = %d", byte[3], byte[4], byte[5], byte[6]);
        }
    }
}

// 0-关机，停止加热；1-1级加热，最小功率；2-2级加热，中等功率；3-3级加热，最大功率
- (void)refreshHotView:(NSInteger)hot {
    if (hot < 0 || hot > 3) {
        return;
    }
    
    NSArray *urlName = @[@"bulb_fire_off",
                         @"bulb_fire_one",
                         @"bulb_fire_two",
                         @"bulb_fire_three"];
    
    NSArray *desStr = @[@"off", @"1000w", @"2000w", @"3000w"];
    
    [self.fireBtn setImage:[UIImage imageNamed:urlName[hot]] forState:UIControlStateNormal];
    self.powerLabel.text = desStr[hot];
    self.powerLabel.hidden = (hot == 0);
}

- (void)refreshHotSlider:(NSInteger)hot {
    NSInteger value[4] = {2, 3, 0, 1};
    float percent = value[hot] / 4.0 + 1.0 / 8.0;
    
    [self.circlularSlider setCurrentValue:percent];
}

#pragma mark - network request
- (void)requestSyncData {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    Byte byte[4] = {0x01, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    
    self.refrshSocket = [[FIPTcpSocket alloc] init];
    [self.refrshSocket sendToServerWithReqType:FIPRequestTypeSync dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
        [self refreshWholeViewWithData:data];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"界面刷新失败"];
    }];
}

- (void)requestRGBWithHot:(NSInteger)hot {
    if (hot < 0 || hot > 3) {
        NSLog(@"Hot的设置参数错误");
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    Byte byte[4] = {hot, 0x00, 0x00, 0x00};
    NSData *data = [NSData dataWithBytes:byte length:4];
    self.hotSocket = [[FIPTcpSocket alloc] init];
    [self.hotSocket sendToServerWithReqType:FIPRequestTypeModifyHot dataByte:data success:^(NSData * _Nonnull data) {
        [hud hideAnimated:YES afterDelay:kHudDelay];
    } failure:^(NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"设置失败"];
        hud.completionBlock = ^(){
            [self requestSyncData];
        };
    }];
}

#pragma mark - getters and setters

@end
